<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
namespace Portal\Controller;

use Common\Controller\HomebaseController;
use Common\Log\TypeLog;
use Label\Model\CategoryModel;
use Order\Model\OrderModel;
use Portal\Model\PostsModel;
use Common\Model\CommentsModel;

class ArticleController extends HomebaseController {

    protected $posts_model;
    protected $page_size;

    function _initialize() {
        parent::_initialize();
        $this->page_size    = 10;
        $this->posts_model  = D("Portal/Posts");
    }

    // 新的文章详情页
    public function article_info()
    {
        $article_id = I('get.id',0,'intval');
        $where      = array(
            'p.post_type'   => \Portal\Model\PostsModel::POST_TYPE_ARTICLE,
            'p.id'          => $article_id,
        );
        $article = $this->posts_model
            ->alias("p")
            ->join("__USERS__ u on p.post_author = u.id", 'left')
            ->field("p.*, (SELECT GROUP_CONCAT(name) FROM rx_label l WHERE FIND_IN_SET(l.id, p.labels) ) as label_names, u.user_nicename, u.avatar")
            ->where($where)
            ->find();

        if (empty($article)) {
            $this->error('这篇文章溜走了。。');
        }

        $this->posts_model->where(array('id' => $article_id))->setInc('post_hits');

        if ($article['labels']) {
            $article['label_names'] = array_slice(array_filter(explode(',', $article['label_names'])), 0, 3);
        }

        // 文章状态是否正常
        $article['can_comment'] = 0;
        if (in_array($article['post_status'], [PostsModel::POST_STATUS_NORMAL])) {
            $article['can_comment'] = 1;
        }

        // 是否专栏作者
        $article['professor'] = 0;
        $pf_info = M('professor')->where(['user_id' => $article['post_author'], 'del_time' => 0])->find();
        if ($pf_info) {
            $article['professor'] = 1;
        }

        $smeta = json_decode($article['smeta'],true);
        $content_data = sp_content_page($article['post_content']);
        $article['post_content'] = $content_data['content'];

        // 二维码
        require_once './plugins/WxPay/lib/phpqrcode.php';
        $file_name  = "article_" . $article_id;
        $url        = 'http://' . C('DOMAIN_NAME') . U('Portal/Article/article_info', ['id' => $article_id]);
        $path       = get_link_qrcode_path($file_name, $url);
        $this->assign('qrcode', $path);

        $this->assign("page",$content_data['page']);
        $this->assign('article', $article);
        $this->assign("smeta", $smeta);
        $this->assign("article_id", $article_id);

        //log
        TypeLog::AddBrowsingLog(get_current_userid(), $article['post_author'], $article_id);

        // 接入分享sdk
        if (C('WX_SHARE')) {
            require_once './plugins/wx_jssdk.php';
            $jssdk       = new \JSSDK(C('WX_OFFICIAL_ACCOUNT.APP_ID'), C('WX_OFFICIAL_ACCOUNT.APP_SECRET'));
            $signPackage = $jssdk->GetSignPackage();
            $this->assign('signPackage', $signPackage);
        }

        // 广告位
        $advertisement = get_ad_by_position(CategoryModel::SLIDESHOW_POSITION_ARTICLE_DETAIL);
        $this->assign('advertisement', $advertisement);

        $this->display(":article");
    }
    
    //文章内页
    public function index() {
    	$article_id = I('get.id',0,'intval');
    	$term_id    = I('get.cid',0,'intval');


    	// 处理用户投稿，未分类的情况
    	$field = "a.*,c.*";
    	$where = ['a.id' => $article_id];
    	if ($term_id) {
    	    $field += ",b.term_id";
    	    $where['b.term_id'] = $term_id;
        }
    	$this->posts_model->alias('a')->field($field);
    	if ($term_id) {
            $this->posts_model->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
        }
        $article = $this->posts_model->join("__USERS__ c ON a.post_author = c.id")->where($where)->find();


        if(empty($article)){
    	    header('HTTP/1.1 404 Not Found');
    	    header('Status:404 Not Found');
    	    if(sp_template_file_exists(MODULE_NAME."/404")){
    	        $this->display(":404");
    	    }
    	    return;
    	}

    	// 文章状态是否正常
    	$article['can_comment'] = 0;
    	if (in_array($article['post_status'], [PostsModel::POST_STATUS_NORMAL])) {
    	    $article['can_comment'] = 1;
        }

        // 是否专栏作者
        $article['professor'] = 0;
        $pf_info = M('professor')->where(['user_id' => $article['post_author'], 'del_time' => 0])->find();
    	if ($pf_info) {
    	    $article['professor'] = 1;
        }

    	if ($term_id) {
            $terms_model = M("Terms");
            $term = $terms_model->where(array('term_id' => $term_id))->find();
            $this->posts_model->where(array('id' => $article_id))->setInc('post_hits');

            $article_date = $article['post_date'];

            $join = '__POSTS__ as b on a.object_id =b.id';
            $join2= '__USERS__ as c on b.post_author = c.id';

            $term_relationships_model= M("TermRelationships");

            $next=$term_relationships_model
                ->alias("a")
                ->join($join)->join($join2)
                ->where(array('b.id'=>array('gt',$article_id),"post_date"=>array("egt",$article_date),"a.status"=>1,'a.term_id'=>$term_id,'post_status'=>1))
                ->order("post_date asc,b.id asc")
                ->find();

            $prev=$term_relationships_model
                ->alias("a")
                ->join($join)->join($join2)
                ->where(array('b.id'=>array('lt',$article_id),"post_date"=>array("elt",$article_date),"a.status"=>1,'a.term_id'=>$term_id,'post_status'=>1))
                ->order("post_date desc,b.id desc")
                ->find();

            $this->assign("next",$next);
            $this->assign("prev",$prev);
        }

    	$smeta=json_decode($article['smeta'],true);
    	$content_data=sp_content_page($article['post_content']);
    	$article['post_content']=$content_data['content'];
    	
    	$this->assign("page",$content_data['page']);
    	$this->assign('article', $article);
    	$this->assign("smeta", $smeta);
    	$this->assign("term", $term);
    	$this->assign("article_id", $article_id);
    	
//    	$tplname=$term["one_tpl"];
//    	$tplname=empty($smeta['template'])?$tplname:$smeta['template'];
//    	$tplname=sp_get_apphome_tpl($tplname, "article");

    	//log
        TypeLog::AddBrowsingLog(get_current_userid(), $article['post_author'], $article_id);

//        var_dump($this->view->get());exit;

    	$this->display(":article");
    }
    
    // 文章点赞
    public function do_like(){
    	$this->check_login();
    	
    	$id         = I('get.id',0,'intval');//posts表中id
        $from_id    = I('get.from_id',0,'intval');//posts表中id
        $userid     = get_current_userid();
    	$can_like   = TypeLog::AddLikeLog($userid, $from_id, $id);
    	
//    	$can_like=sp_check_user_action("posts$id",1);
    	
    	if($can_like['status'] == 1){
            $posts_model=M("Posts");
    		$posts_model->save(array("id" => $id, "post_like" => array("exp", "post_like + 1")));
    		$this->success($can_like['msg']);
    	}else{
    		$this->error($can_like['msg']);
    	}
    }

	  // 文章登陆
    public function do_login(){
    	$this->check_login();
    }
    
    // 前台用户添加文章
    public function add(){
        $this->check_login();
        $this->assign(sp_get_current_user());
        $this->_getTermTree();
        $this->display();
    }
    
    // 前台用户添加文章提交
    public function add_post(){
        if(IS_POST){
            $this->check_login();

            if(empty($_POST['term'])){
                $this->error("请至少选择一个分类！");
            }
            $posts_model=M('Posts');
            $term_relationships_model=M('TermRelationships');
            
            $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            
            $_POST['post']['post_date']=date("Y-m-d H:i:s",time());
            $_POST['post']['post_modified']=date("Y-m-d H:i:s",time());
            $_POST['post']['post_author']=sp_get_current_userid();
            $article=I("post.post");
            $article['smeta']=json_encode($_POST['smeta']);
            $article['post_content']=safe_html(htmlspecialchars_decode($article['post_content']));
            if ($posts_model->field('post_date,post_author,post_content,post_title,post_modified,smeta')->create($article)!==false) {
                $result=$posts_model->add();
                if ($result) {
                    $result=$term_relationships_model->add(array("term_id"=>intval($_POST['term']),"object_id"=>$result));
                    if($result){
                        $this->success("文章添加成功！");
                    }else{
                        $posts_model->delete($result);
                        $this->error("文章添加失败！");
                    }
                
                } else {
                    $this->error("文章添加失败！");
                }
            }else{
                $this->error($posts_model->getError());
            }
        }
    
    }
    
    // 前台用户文章编辑
    public function edit(){
        $this->check_login();
        $id         = I("get.id", 0, 'intval');
        $user_id    = sp_get_current_userid();
        $posts_model=M('Posts');

        $this->assign(sp_get_current_user());

        if ($id) {
            // 编辑
            $post = $posts_model->where(array('id' => $id, 'post_author' => $user_id))->find();
            $this->assign("post",$post);
            $this->assign("smeta",json_decode($post['smeta'],true));

            // 审核信息
            $comment_model  = M('Comments');
            $where          = array("post_table" => 'posts', "post_id" => $id, 'type' => CommentsModel::COMMENT_TYPE_JUDGE_INFO);
            $judge_lists    = $comment_model->where($where)->limit(0)->order("createtime desc")->select();
            $judge_lists    = array_map(function ($v) {
                $content = $v['content'];
                list($reason, $suggest) = explode('||', $content);
                !empty($reason) && $v['reason'] = $reason;
                !empty($suggest) && $v['suggest'] = $suggest;
                return $v;
            }, $judge_lists);
            $this->assign('judge_list', $judge_lists);
        }
        $this->display();
    }
    
    // 前台用户文章编辑提交
    public function edit_post(){
        $this->check_login();

        $posts_model    = M('Posts');
        $user           = sp_get_current_user();
        $id             = I('post.id', 0, 'intval');
        $status         = I('get.status', 0, 'intval');

        $_POST['smeta']['thumb']                = sp_asset_relative_url($_POST['smeta']['thumb']);
        $_POST['post']['post_modified']         = date("Y-m-d H:i:s",time());
        $_POST['post']['post_author']           = $user['id'];
        $_POST['post']['post_type']             = PostsModel::POST_TYPE_ARTICLE;
        $_POST['post']['post_author_name']      = $user['user_nicename'] ?: $user['user_login'];
        $_POST['post']['post_status']           = $status;
        $article                                = I("post.post");
        $article['smeta']                       = json_encode($_POST['smeta']);
        $article['post_content']                = safe_html(htmlspecialchars_decode($article['post_content']));

        if (empty($article['id'])) {
            unset($article['id']);
        }

        if ($id) {
            // 编辑
            $result = $posts_model->where(array('id'=>$article['id'],'post_author'=>$user['id']))->save($article);
        } else {
            // 新增
            $article['post_date'] = date("Y-m-d H:i:s", time());
            $result = $posts_model->add($article);
        }
        if ($result !== false) {
            $this->success("文章编辑成功！");
        } else {
            $this->error("文章编辑失败！");
        }
    }
    
    // 获取文章分类树结构
    private function _getTermTree($term=array()){
        $result =M('Terms')->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=in_array($r['term_id'], $term)?"selected":"";
            $r['checked'] =in_array($r['term_id'], $term)?"checked":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $terms = $tree->get_tree(0, $str);
        $this->assign('terms', $terms);
    }

    // 我的投稿
    public function user_article()
    {
        $this->check_login();
        $user_id    = sp_get_current_userid();
        $status     = I('get.status', 0, 'intval');
        $where      = ['post_status' => $status, 'post_type' => PostsModel::POST_TYPE_ARTICLE, 'post_author' => $user_id];
        $count      = $this->posts_model->where($where)->count();
        $page       = $this->page($count, $this->page_size);

        // 文章数统计
        $where_count    = ['post_type' => PostsModel::POST_TYPE_ARTICLE, 'post_author' => $user_id];
        $status_counts  = $this->posts_model->where($where_count)->field('post_status, count(*) as status_count')->group('post_status')->select();
        $status_c       = array();
        foreach ($status_counts as $v) {
            $status_c[$v['post_status']] = $v['status_count'];
        }
        $this->assign('status_counts', $status_c);


        // 判断分页数
        $page_parm  = C("VAR_PAGE");
        if (I($page_parm) > ceil($count / $this->page_size)) {
            $this->error('没有更多数据了');
        }

        $articles   = $this->posts_model
            ->where($where)
            ->limit($page->firstRow, $page->listRows)
            ->order('post_modified desc')
            ->select();

        $this->assign("page", $page->show('default'));
        $this->assign("articles", $articles);
        $this->assign('status', $status);
        $this->assign(sp_get_current_user());
        $this->assign('count', $count);
        $this->assign('total_pages', ceil($count / $this->page_size));
        $this->display();
    }

    // 日报列表
    public function daily_report_list()
    {
        $where = array(
            'p.post_status'     => PostsModel::POST_STATUS_NORMAL,
            'p.post_type'       => PostsModel::POST_TYPE_DAILY_REPORT,
            'p.post_date'       => ['ELT', date("Y-m-d H:i:s")],
        );
        $model      = M('posts');
        $count      = $model->alias('p')->where($where)->count();
        $page       = $this->page($count, $this->page_size);
        $lists      = $model
            ->alias('p')
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("post_date desc")
            ->select();
        $back_img = array(
            sp_get_asset_upload_path('http://video.rixins.com/image/default/3A8965BD580040C4B30F94905876B703-6-2.jpg'),
            sp_get_asset_upload_path('http://video.rixins.com/image/default/34C9C1E7AFFC486DA48E6301C73A20E2-6-2.jpg'),
            sp_get_asset_upload_path('http://video.rixins.com/image/default/C9ED79757677477CAEF0ACFA5B28C0A2-6-2.jpg'),
            sp_get_asset_upload_path('http://video.rixins.com/image/default/AD4DABB96E484D14A4C1530B89A00BDB-6-2.jpg'),
            sp_get_asset_upload_path('http://video.rixins.com/image/default/A6D019E02FF5422086C938FADD651F0C-6-2.jpg')
        );
        foreach ($lists as $k => $v) {
            $week = date('w', strtotime($v['post_date']));
            if ($week == 6 || $week == 0) {
                $v['back_img'] = $back_img[0];
            } else {
                $v['back_img'] = $back_img[$week - 1];
            }
            $lists[$k] = $v;
        }

        $this->assign('count', $count);
        $this->assign("page", $page->show('default'));
        $this->assign("lists", $lists);
        $this->assign("total_page", ceil($count / $this->page_size));
        $this->display();
    }
    
    // 日报详情
    public function daily_report_detail()
    {
        $article_id = I('get.id',0,'intval');
        $where      = array(
            'p.post_type'   => PostsModel::POST_TYPE_DAILY_REPORT,
            'p.id'          => $article_id,
            'p.post_status' => PostsModel::POST_STATUS_NORMAL,
        );
        $article = $this->posts_model
            ->alias("p")
            ->join("__USERS__ u on p.post_author = u.id", 'left')
            ->field("p.*, u.user_nicename, u.avatar")
            ->where($where)
            ->find();

        if (empty($article)) {
            $this->error('这篇早报溜走了。。');
        }

        $this->posts_model->where(array('id' => $article_id))->setInc('post_hits');

        // 文章状态是否正常
        $article['can_comment'] = 0;
        if (in_array($article['post_status'], [PostsModel::POST_STATUS_NORMAL])) {
            $article['can_comment'] = 1;
        }

        $smeta = json_decode($article['smeta'],true);
        $content_data = sp_content_page($article['post_content']);
        $article['post_content'] = $content_data['content'];

        $this->assign("page",$content_data['page']);
        $this->assign('article', $article);
        $this->assign("article_id", $article_id);

        //log
        TypeLog::AddBrowsingLog(get_current_userid(), $article['post_author'], $article_id);

        // 二维码
        require_once './plugins/WxPay/lib/phpqrcode.php';


        $file_name  = "daily_report_" . $article_id;
        $url        = 'http://' . C('DOMAIN_NAME') . U('Portal/Article/daily_report_detail', ['id' => $article_id]);
        $path       = get_link_qrcode_path($file_name, $url);
        $this->assign('qrcode', $path);

        // 接入分享sdk
        if (C('WX_SHARE')) {
            require_once './plugins/wx_jssdk.php';
            $jssdk       = new \JSSDK(C('WX_OFFICIAL_ACCOUNT.APP_ID'), C('WX_OFFICIAL_ACCOUNT.APP_SECRET'));
            $signPackage = $jssdk->GetSignPackage();
            $this->assign('signPackage', $signPackage);
        }
        $this->display();
    }

}
